package logic

import (
	"context"
	"fmt"
	"vipshop/model/mysql"
	"vipshop/model/redis"
	"vipshop/pkg"

	"vipshop/userrpc/internal/svc"
	"vipshop/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *userrpc.UserRegisterRequest) (*userrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("captcharegister" + in.Tel)
	if get.Val() != in.Captchacode {
		return nil, fmt.Errorf("图形验证码不正确，请重新输入")
	}

	cmd := redis.Client.Get("sendSmsregister" + in.Tel)
	if cmd.Val() != in.Sendsmscode {
		return nil, fmt.Errorf("短信验证码不正确，请重新输入")
	}
	var finduser mysql.User
	mysql.DB.Debug().Model(&mysql.User{}).Where("tel=?", in.Tel).Find(&finduser)
	if finduser.ID != 0 {
		return nil, fmt.Errorf("该手机号已经注册，请重新输入")
	}
	user := mysql.User{
		Tel:      in.Tel,
		Password: pkg.PwdMD5(in.Password),
	}
	mysql.DB.Debug().Model(&mysql.User{}).Create(&user)
	redis.Client.Del("captcharegister" + in.Tel)
	redis.Client.Del("sendSmsregister" + in.Tel)

	return &userrpc.UserRegisterResponse{Id: int64(user.ID)}, nil
}
